package com.duke.payphone.acct;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.R;
import com.duke.payphone.RootActivity;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * This activity will only be called by the login screen. To help the user
 * create
 * a new account.
 * 
 * username, password, phone number, set pin, first name, last name
 * 
 * It needs to check the validity of the information.
 * Then it sends it to the server.. another check.. server could respond = not
 * valid.
 * ex. user name taken, password taken... no repeats
 * 
 * If the server responds valid, toast = "account created", back to login screen
 * 
 * If not valid, toast = "account creation failed", stay at this screen
 * 
 * 
 * Buttons: create, cancel (back to login screen)
 * 
 * @author Michael
 * 
 */
public class AccountCreateActivity extends Activity {

    private Global globalvars;

    private EditText user;
    private EditText pswd;
    private EditText fn;
    private EditText ln;

    private String userStr;
    private String pswdStr;
    private String fnStr;
    private String lnStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_create);

        globalvars = (Global) getApplicationContext();

        user = (EditText) findViewById(R.id.et_user);
        pswd = (EditText) findViewById(R.id.et_pswd);
        fn = (EditText) findViewById(R.id.et_fn);
        ln = (EditText) findViewById(R.id.et_ln);
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_account_create, menu);
        // return true;
        return false;
    }

    public void executeBack (View v) {
        finish();
    }

    public void executeCreate (View v) {
        updateData();

        // check validity
        if (checkData()) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                // if (response.containsKey("session") &&
                // response.get("session").equals("valid")) {

                if (response.containsKey("result") && response.get("result").equals("valid")) {
                    onNewUserValid(response);
                }
                else {
                    onNewUserInvalid(response);
                }
                // }
                // else {
                // onSessionInvalid(); // does not happen for login or newuser
                // }
            }
            else {
                onServerInvalid();
            }
        }

    }

    /**
     * Rereads the data from text fields
     */
    private void updateData () {
        userStr = user.getText().toString();
        pswdStr = pswd.getText().toString();
        fnStr = fn.getText().toString();
        lnStr = ln.getText().toString();
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {

        // reset sessionID
        Global.sessionid = "";

        // create map
        Map<String, Serializable> request = MapFactory.createTransmitMap("newuser");
        request.put("username", userStr);
        request.put("password", pswdStr);
        request.put("firstname", fnStr);
        request.put("lastname", lnStr);
        return request;
    }

    private boolean checkData () {
        // verify data is correct
        if (userStr.isEmpty() || pswdStr.isEmpty() || fnStr.isEmpty() || lnStr.isEmpty()) {
            // if incorrect, toast: [how to correct the data]
            Toast.makeText(globalvars, "All fields are required.", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * new user account created
     * 
     * @param response
     */
    private void onNewUserValid (Map<String, Serializable> response) {
        // save sessionid
        if (response.containsKey("sessionid")) {
            Global.sessionid = (String) response.get("sessionid");
        }
        
        // save username
        if (response.containsKey("username")){
            Global.username = (String) response.get("username");
        }

        Toast.makeText(globalvars, "Account creation successful.", Toast.LENGTH_SHORT).show();

        // start root activity
        Intent toRoot = new Intent(this, RootActivity.class);
        startActivity(toRoot);
        finish();
    }

    /**
     * new user not created
     * 
     * @param response
     */
    private void onNewUserInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Username taken. Account creation unsuccessful.",
                       Toast.LENGTH_SHORT).show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    // /**
    // * If session has timed out
    // */
    // private void onSessionInvalid () {
    // // reset the sessionID to null
    // Global.sessionid = "";
    //
    // // toast: current session has timed out
    // Toast.makeText(globalvars, "Current session has timed out.",
    // Toast.LENGTH_SHORT).show();
    //
    // // go back to the login screen
    // Intent toLogin = new Intent(this, LoginActivity.class);
    // toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // startActivity(toLogin);
    // finish();
    // }

}
